package cn.stylefeng.guns.modular.yingbao.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.yingbao.entity.SysUser;
import cn.stylefeng.guns.modular.yingbao.entity.SysUserGroup;
import cn.stylefeng.guns.modular.yingbao.entity.UserMoney;
import cn.stylefeng.guns.modular.yingbao.entity.UserMy;
import cn.stylefeng.guns.modular.yingbao.handler.GroupHandler;
import cn.stylefeng.guns.modular.yingbao.mapper.SysUserMapper;
import cn.stylefeng.guns.modular.yingbao.mapper.UserMoneyMapper;
import cn.stylefeng.guns.modular.yingbao.mapper.UserMyMapper;
import cn.stylefeng.guns.modular.yingbao.model.params.SysUserParam;
import cn.stylefeng.guns.modular.yingbao.model.result.SysUserResult;
import cn.stylefeng.guns.modular.yingbao.service.SysUserGroupService;
import  cn.stylefeng.guns.modular.yingbao.service.SysUserService;
import cn.stylefeng.guns.modular.yingbao.service.UserMoneyService;
import cn.stylefeng.guns.modular.yingbao.service.UserMyService;
import cn.stylefeng.guns.modular.yingbao.util.Pigeon;
import cn.stylefeng.guns.modular.yingbao.util.RandomNum;
import cn.stylefeng.guns.modular.yingbao.util.StringUtil;
import cn.stylefeng.guns.redis.RedisUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.MD5Util;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhyd.oauth.utils.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * <p>
 * 盈宝用户表 服务实现类
 * </p>
 *
 * @author zs
 * @since 2019-12-10
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {


    /****
     * 注入配置文件数据
     */
    @Value("${spring.redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    //过期时间60秒
    @Value("${spring.redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;

    @Autowired
    UserMoneyService userMoneyMapper;
    @Autowired
    RedisUtil redis;
    @Autowired
    UserMyService userMyService;
    @Autowired
    SysUserGroupService sysUserGroupService;
    @Lazy
    @Autowired
    GroupHandler groupHandler;
    @Autowired
    SysUserMapper sysUserMapper;
    @Override
    public void add(SysUserParam param){
        SysUser entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(SysUserParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(SysUserParam param){
        SysUser oldEntity = getOldEntity(param);
        SysUser newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public SysUserResult findBySpec(SysUserParam param){
        return null;
    }

    @Override
    public List<SysUserResult> findListBySpec(SysUserParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(SysUserParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageLists(pageContext, param);
        LayuiPageInfo pageInfo = LayuiPageFactory.createPageInfo(page);
        System.out.println(pageInfo.toString());
        return pageInfo;
    }

    public String queryByCode(String s){
        while (this.baseMapper.selectOne(new QueryWrapper<SysUser>().eq("referrer_code",s)) != null){
            s = RandomNum.generateShortUuid();
        }
        return s;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData addLogin(SysUser user) {
        String o = (String)redis.get(REDIS_KEY_PREFIX_AUTH_CODE + user.getPhone());
        if(user.getSalt().equals(o)) {
            redis.del(REDIS_KEY_PREFIX_AUTH_CODE + user.getPhone());
            if (user != null && !StringUtils.isEmpty(user.getAccount())) {

                if(!user.getAccount().matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,11}$")){
                //if (user.getAccount().length() < 4 || user.getAccount().length() > 11 || !StringUtil.isEnglish(user.getAccount())) {
                    return ResponseData.error(500, "用户名格式错误");
                }else {
                    SysUser name = this.baseMapper.selectOne(new QueryWrapper<SysUser>().eq("account", user.getAccount()));
                    if (name != null) {
                        return ResponseData.error(500, "用户名已存在");
                    }
                }
            }
            if (user.getPassword() == null || user.getPassword().length() < 5 || user.getPassword().length() > 19) {
                return ResponseData.error(500, "密码必须大于6位或者不能为空");
            }
            if (user != null && user.getPhone().length() != 11) {
                return ResponseData.error(500, "手机号格式错误");
            } else {
                List<Object> referrerCode = this.baseMapper.selectObjs(new QueryWrapper<SysUser>().eq("phone", user.getPhone()));
                if (referrerCode.size() == 5) {
                    return ResponseData.error(500, "手机号注册已经到达上限");
                }
            }
            if (user != null) {
                if (user.getReferrerCode() != null && user.getReferrerCode() != 0 && String.valueOf(user.getReferrerCode()).length() > 6) {
                //if (!StringUtils.isEmpty(String.valueOf(user.getReferrerCode())) || !"".equals(String.valueOf(user.getReferrerCode())) || null != user.getReferrerCode()) {
                    SysUser use = this.baseMapper.selectOne(new QueryWrapper<SysUser>().eq("referrer_code", user.getReferrerCode()));
                    if(user.getReferrerCode() == null || use == null){
                        return ResponseData.error(500,"请输入正确的邀请码");
                    }
                    user.setReferrerId(use.getId());
                    user.setReferrer(use.getName());
                    user.setReferrerCode(1L);
                } else {
                    user.setReferrerId(0L);
                    user.setReferrer("0");
                    user.setReferrerCode(1L);
                }
            }
            //图片
            user.setAvatar(String.valueOf(0));
            user.setIsNewbie(1);
            user.setSalt(String.valueOf(RandomNum.random()));
            String encrypt = MD5Util.encrypt(user.getPassword() + user.getSalt());
            user.setPassword(encrypt);
            user.setVersion(1L);
            user.setAvatar("/ueditor/images/1214362685131509761.png");
            user.setAuthenticationId(0L);
            user.setVipId(0L);
            user.setIsLogin(0);
            user.setBackup1("0");
            user.setBackup2("0");
            user.setBackup3("0");
            user.setBackup4("0");
            user.setStatus("0");
            int x = this.baseMapper.insert(user);
            if (x > 0) {
                UserMoney userMoney = new UserMoney();
                userMoney.setUserid(user.getId());
                userMoney.setFrozenCapital(0L);
                userMoney.setAvailMoney(0L);
                userMoney.setExpandMoney(0L);
                userMoney.setRebateMoney(0L);
                userMoney.setVersion(1L);
                userMoney.setCabinMoney(0L);
                userMoney.setBackup1(0L);
                userMoney.setBackup2("0");
                userMoney.setBackup3("0");
                userMoney.setBackup4("0");
                userMoney.setBackup5("0");
                boolean insert = userMoneyMapper.save(userMoney);
                if (insert) {
                    int i = (int) ((Math.random() * 9 + 1) * 1000000);
                    while (userMyService.getById(i) != null){
                        i = (int) ((Math.random() * 9 + 1) * 1000000);
                    }
                    UserMy userMy = new UserMy();
                    userMy.setId(i);
                    userMy.setBackup1(user.getAccount());
                    userMy.setBackup2(user.getAccount());
                    userMy.setBackup4(user.getAccount());
                    userMy.setBackup3(user.getAccount());
                    userMy.setBackup6(user.getId());
                    userMy.setName(user.getAccount());
                    userMy.setPic("/ueditor/images/1214362685131509761.png");
                    ResponseData responseData = this.userMyService.addMyUser(userMy);
                    if(responseData.getCode() != 200){
                        throw new UnsupportedOperationException("失败1");
                    }
                    user.setReferrerCode(userMy.getId().longValue());
                    int id = this.baseMapper.update(user, new QueryWrapper<SysUser>().eq("id", user.getId()));

                    if(id > 0){
                        SysUserGroup sysUserGroup = new SysUserGroup();
                        sysUserGroup.setUserid(user.getId());
                        sysUserGroup.setIsNewbie(1);
                        sysUserGroup.setVersion(1);
                        sysUserGroup.setGroupOrdinalSize(0L);
                        sysUserGroup.setGrade(0);
                        sysUserGroup.setMoney(0L);
                        sysUserGroup.setAvatar(userMy.getPic());
                        sysUserGroup.setOrdinalSize(0L);
                        sysUserGroup.setGroupSize(0);
                        sysUserGroup.setReferrerId(user.getReferrerId());
                        sysUserGroup.setUserName(user.getAccount());
                        SysUser sysUser = this.baseMapper.selectById(user.getReferrerId());
                        if(sysUser == null ){
                            sysUserGroup.setSjReferrerId(0L);
                        }else {
                            sysUserGroup.setSjReferrerId(sysUser.getReferrerId());
                        }
                        boolean save = sysUserGroupService.save(sysUserGroup);
                        if(!save){
                            throw new UnsupportedOperationException("失败2");
                        }
                        SysUserGroup userid = sysUserGroupService.getOne(new QueryWrapper<SysUserGroup>().eq("userid", sysUserGroup.getReferrerId()));
                        if(userid == null){
                            return ResponseData.success();
                        }
                        userid.setGroupSize(userid.getGroupSize()+1);
                        int version = userid.getVersion();
                        userid.setVersion(userid.getVersion()+1);
                        boolean update = sysUserGroupService.update(userid, new QueryWrapper<SysUserGroup>().eq("id", userid.getId()).eq("version", version));
                        if(!update){
                            throw new UnsupportedOperationException("失败3");
                        }

                        SysUserGroup userids = sysUserGroupService.getOne(new QueryWrapper<SysUserGroup>().eq("userid", sysUserGroup.getSjReferrerId()));
                        if(userids == null){
                            return ResponseData.success();
                        }
                        userids.setGroupSize(userids.getGroupSize()+1);
                        int versions = userids.getVersion();
                        userids.setVersion(userids.getVersion()+1);
                        boolean updates = sysUserGroupService.update(userids, new QueryWrapper<SysUserGroup>().eq("id", userids.getId()).eq("version", versions));
                        if(!updates){
                            throw new UnsupportedOperationException("失败4");
                        }
                        groupHandler.group(String.valueOf(userids.getUserid()));
                        return ResponseData.success(200, "成功", user.getId());
                    }
                    throw new UnsupportedOperationException("失败");
                } else {
                    this.baseMapper.deleteById(user.getId());
                }
            }
            return ResponseData.error(50, "注册失败");
        }
        return ResponseData.error(500,"  验证码错误");
    }


    @Override
    public ResponseData queryByNameAndPassword(String name, String password) {
        if(name == null || password == null){
            return ResponseData.error(500,"账号或密码不能为空");
        }
        SysUser user1 = this.baseMapper.selectOne(new QueryWrapper<SysUser>().eq("account",name));
        if(user1 == null){
            return ResponseData.error(500,"账号不存在");
        }
        String salt = user1.getSalt();
        String encrypt = MD5Util.encrypt(password + salt);
        SysUser user = this.baseMapper.selectOne(new QueryWrapper<SysUser>().eq("account", name).eq("password", encrypt));
        if(user != null){
            return ResponseData.success(200,"成功",user);
        }
        return ResponseData.error(500,"账号或密码错误");

    }

    @Override
    public ResponseData forgetPassword(String account, String phone, String code, String password) {
            String o = (String)redis.get(REDIS_KEY_PREFIX_AUTH_CODE + phone);
            if(code.equals(o)) {
                redis.del(REDIS_KEY_PREFIX_AUTH_CODE + phone);
                SysUser sysUser = this.baseMapper.selectOne(new QueryWrapper<SysUser>().eq("account", account));
                if(sysUser == null){
                    return ResponseData.error(500,"请输入正确的用户名");
                }
                if (!"".equals(phone) ||StringUtils.isNotEmpty(phone)) {
                    if(phone.equals(sysUser.getPhone())) {
                        Integer random = RandomNum.random();
                        sysUser.setPassword(MD5Util.encrypt(password + random));
                        sysUser.setSalt(String.valueOf(random));
                        int i = this.baseMapper.updateById(sysUser);
                        if (i > 0) {
                            return ResponseData.success(200, "修改成功", "123123");
                        }
                        return ResponseData.error(500, "修改失败,重试下");
                    }
                }
                return ResponseData.error(500, "请输入正确手机号");
            }
            return ResponseData.error(500,"验证码错误");
    }

    @Override
    public ResponseData queryByNameAndPhoneSeekMoneyPassword(String account, String phone) {
        SysUser sysUser = this.baseMapper.selectOne(new QueryWrapper<SysUser>().eq("account", account).eq("phone", phone));
        if(sysUser != null && !StringUtils.isEmpty(sysUser.getMoneyPassword())){
            return ResponseData.success(200,"修改交易密码",null);
        }
        return ResponseData.error(500,"请输入密码");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData upMoneyPassword(String account, String phone, String code, String moneyPassword,String newMoneyPassword) {
        String o = (String)redis.get(REDIS_KEY_PREFIX_AUTH_CODE + phone);
        if(code.equals(o)) {
            redis.del(REDIS_KEY_PREFIX_AUTH_CODE + phone);
            SysUser sysUser = this.baseMapper.selectOne(new QueryWrapper<SysUser>().eq("account", account).eq("phone", phone));
            if (sysUser != null) {
                if(StringUtils.isNotEmpty(sysUser.getMoneyPassword())){
                    if(moneyPassword == null || "".equals(moneyPassword)){
                        return ResponseData.error(500,"请输入原密码");
                    }
                    if(!sysUser.getMoneyPassword().equals(MD5Util.encrypt(moneyPassword))){
                        return ResponseData.error(500,"与原密码不相符");
                    }
                }
                /*if(StringUtils.isNotEmpty(sysUser.getMoneyPassword()) && StringUtils.isNotEmpty(moneyPassword)){
                    if(!sysUser.getMoneyPassword().equals(MD5Util.encrypt(moneyPassword))){
                        return ResponseData.error(500,"与原密码不相符");
                    }
                }*/
                Long version = sysUser.getVersion();
                sysUser.setMoneyPassword(MD5Util.encrypt(newMoneyPassword));
                sysUser.setVersion(version + 1);
                int update = this.baseMapper.
                        update(sysUser, new QueryWrapper<SysUser>().eq("account", account).eq("phone", phone).eq("version", version));
                if (update > 0) {
                    return ResponseData.success(
                            200, "修改成功", null);
                }
                return ResponseData.error(500, "修改失败");
            }
            return ResponseData.error(500,"暂无此人");
        }
        return ResponseData.error(500,"验证码错误");
    }

    @Override
    public ResponseData queryByPhone(String phone) {
        if(StringUtils.isEmpty(phone) || phone.length() != 11){
            return ResponseData.error(500,"手机号格式不正确");
        }
        Object o = redis.get(REDIS_KEY_PREFIX_AUTH_CODE + phone);
        if (o!=null){
            return ResponseData.error(500,"验证码已发送");
        }
        StringBuilder sb = new StringBuilder();
                Random random = new Random();
                for(int i=0;i<6;i++){
                    sb.append(random.nextInt(10));
        }

        String result = "false";
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                List<BasicNameValuePair> formparams = new ArrayList<>();
                formparams.add(new BasicNameValuePair("Account", Pigeon.getAccount()));
                formparams.add(new BasicNameValuePair("Pwd",Pigeon.getPwd()));//登录后台 首页显示
                formparams.add(new BasicNameValuePair("Content","您的验证码是"+sb));
                formparams.add(new BasicNameValuePair("Mobile",phone));
                formparams.add(new BasicNameValuePair("SignId",Pigeon.getSignid()));//登录后台 添加签名获取id

                HttpPost httpPost = new HttpPost("http://api.feige.ee/SmsService/Send");
                httpPost.setEntity(new UrlEncodedFormEntity(formparams,"UTF-8"));
                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity);
                System.out.println(result);
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(result.contains("OK")){
            System.out.println(REDIS_KEY_PREFIX_AUTH_CODE+phone);
            redis.set(REDIS_KEY_PREFIX_AUTH_CODE+phone,sb);
            redis.expire(REDIS_KEY_PREFIX_AUTH_CODE+phone,AUTH_CODE_EXPIRE_SECONDS);
            return ResponseData.success(200,"获取验证码成功",null);
        }
        return ResponseData.error(500,"未知错误");
    }

    @Override
    public ResponseData queryById(long l) {
        SysUser sysUser = this.baseMapper.selectById(l);
        return ResponseData.success(sysUser.getAccount());
    }

    @Override
    public ResponseData queryByMoneyPassword(Long id, String moneyPassword) {
        if(id == null || StringUtils.isEmpty(moneyPassword)){
            return ResponseData.error(500,"参数错误");
        }
        SysUser sysUser = this.baseMapper.selectById(id);
        if(sysUser == null) {
            return ResponseData.error(500,"此人不存在");
        }
        if(StringUtils.isEmpty(sysUser.getMoneyPassword())) {
            return ResponseData.error("请先设置资金密码");
        }
        if (sysUser.getMoneyPassword().equals(MD5Util.encrypt(moneyPassword))){
            return ResponseData.success();
        }
        return ResponseData.error(500,"密码错误");
    }

    private Serializable getKey(SysUserParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private SysUser getOldEntity(SysUserParam param) {
        return this.getById(getKey(param));
    }

    private SysUser getEntity(SysUserParam param) {
        SysUser entity = new SysUser();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    public static void main(String[] args) {
        System.out.println(1000*60*2);
    }

}
